//
//  ViewController.m
//  24_MD5
//
//  Created by dllo on 16/8/16.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ViewController.h"
#import "AFNetworking.h"
#import "NSString+DKMD5.h"

@interface ViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *encryptText;
@property (weak, nonatomic) IBOutlet UITextField *decipherText;
- (IBAction)encryptAction:(id)sender;
- (IBAction)decipherAction:(id)sender;
- (IBAction)md5Action:(id)sender;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)encryptAction:(id)sender {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postUrlString = @"http://tool.zzblo.com/api/md5/encrypt";
    NSString *parameters = [NSString stringWithFormat:@"text=%@", _encryptText.text];
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return parameters;
    }];
    [manager POST:postUrlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"加密成功: %@", responseObject);
        _decipherText.text = responseObject[@"secret16"];
        _encryptText.text = nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
    }];
}

- (IBAction)decipherAction:(id)sender {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postUrlString = @"http://tool.zzblo.com/api/md5/decrypt";
    NSString *parameters = [NSString stringWithFormat:@"secret=%@", _decipherText.text];
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return parameters;
    }];
    [manager POST:postUrlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"解密成功: %@", responseObject);
        _encryptText.text = responseObject[@"text"];
        _decipherText.text = nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
    }];
}

- (IBAction)md5Action:(id)sender {
    _decipherText.text = [_decipherText.text stringWith16BitMD5Lower];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField endEditing:YES];
    return YES;
}
@end
